package org.visionlibrary.image.filters.adjustement;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class ExtractColor extends AbstractFilter {
	private int[] schannels = { 180, 180, 0 };
	private double tollerance = 110.0d;
	
	public int[] getSchannels() {
		return schannels;
	}

	public void setSchannels(int[] schannels) {
		this.schannels = schannels;
	}

	public double getTollerance() {
		return tollerance;
	}

	public void setTollerance(double tollerance) {
		this.tollerance = tollerance;
	}
	
	public ExtractColor(int[] schannels, double tollerance) {
		this.schannels = schannels;
		this.tollerance = tollerance;
	}

	@Override
	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);
		
		int maxX = src.getWidth();
		int maxY = src.getHeight();

		int[] channels = new int[src.getNumBands()];
	
		for (int x = 0; x < maxX; x++)
			for (int y = 0; y < maxY; y++) {
				for (int ch = 0; ch < src.getNumBands(); ch++) {
					channels[ch] = src.getSample(x, y, ch);
				}
				for (int i = 0; i < channels.length; i++) {
					int channelsum = 0;
					for (int j = 0; j < channels.length; j++) {
						channelsum += (channels[j] - schannels[j])
								* (channels[j] - schannels[j]);
					}
					double difference = Math.sqrt(channelsum);

					if (difference < tollerance)
						for (int k = 0; k < channels.length; k++)
							dest.setSample(x, y, k, channels[k]);
					else
						for (int k = 0; k < channels.length; k++)
							dest.setSample(x, y, k, 0);
				}
			}

		return dest;
	}
	
	@Override
	public String toString() {
		return new String("Adjustement>Extract Color");
	}
}